package com.achobeta.recruitment.controller.student;

import com.achobeta.recruitment.common.AppResult;
import com.achobeta.recruitment.common.ResultCode;
import com.achobeta.recruitment.common.Rule;
import com.achobeta.recruitment.model.*;
import com.achobeta.recruitment.model.vo.StudentInfoVO;
import com.achobeta.recruitment.service.student.StudentInfoService;
import com.achobeta.recruitment.utils.CheckUtils;
import com.achobeta.recruitment.utils.LimitUtils;
import com.achobeta.recruitment.utils.MediaUtils;
import com.achobeta.recruitment.utils.SessionUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.*;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 马拉圈
 * Date: 2023-10-30
 * Time: 17:02
 */
@Api(tags = "学生信息相关")
@Slf4j
@RestController
@RequestMapping("/studentinfo")
public class StudentInfoController {

    @Autowired
    private StudentInfoService studentInfoService;

    @ApiOperation(value = "查询草稿", notes = "data就是简历的草稿信息，StudentInfoWithBLOBs")
    @GetMapping("/select")
    public AppResult<Map<String, Object>> selectStudentInfo(HttpServletRequest request) {
        // 获取当前登录用户openid
        WxUser wxUser = SessionUtils.getWxUser(request);
        String openid = wxUser.getOpenid();
//        String openid = guy;
        // 获取当前登录用户的简历草稿
        StudentInfoWithBLOBs studentInfo = studentInfoService.selectStudentInfoByOpenId(openid, (byte) 0);
        StudentInfoWithBLOBs studentInfoSubmit = studentInfoService.selectStudentInfoByOpenId(openid, (byte) 1);
        // 校验
        if(studentInfo == null || studentInfo.getDeleteState() == 1) {
            log.warn(ResultCode.FAILED_UNAUTHORIZED.toString());
            return AppResult.failed(ResultCode.FAILED_UNAUTHORIZED);
        }
        // 返回数据
        Map<String, Object> map = new HashMap<>();
        map.put("studentInfo", studentInfo);
        map.put("isSubmit", studentInfoSubmit != null);
        return AppResult.success(map);
    }

    @ApiOperation(value = "上传头像", notes = "data是保存的路径，String")
    @PostMapping("/picture")
    public AppResult<String> picture(@ApiParam("头像") @NonNull @RequestPart("photo") MultipartFile file) throws IOException {
        CheckUtils.checkNULL(file);
        // 获取一个路径
        String originName = file.getOriginalFilename();
        // 校验类型
        CheckUtils.checkImage(originName.substring(originName.lastIndexOf(".")));
        String path = MediaUtils.getImageUniquePath(originName);
        CheckUtils.checkNULL(path);
        // 下载文件
        studentInfoService.loadImage(file, path);
        // 返回成功（路径）
//        path = "http://" + redirectDomain + "/" + path;//改为全路径
        return AppResult.success("上传成功", path);
    }

    @ApiOperation(value = "上传头像(管理员修改学生信息用)", notes = "data是保存的路径，String")
    @PostMapping("/manager/picture")
    public AppResult<String> managerPicture(HttpServletRequest request,
                                            @ApiParam("头像") @NonNull @RequestPart("photo") MultipartFile file) throws IOException {
        Manager manager = SessionUtils.getManager(request);
        // 判断是否有权限
        if(!LimitUtils.hasPower(manager, Rule.UPLOAD_STUDENT_PICTURE_RULE)) {
            log.warn(ResultCode.FAILED_MANAGER_NOT_POWERS.toString());
            return AppResult.failed(ResultCode.FAILED_MANAGER_NOT_POWERS);
        }
        // 获取一个路径
        CheckUtils.checkNULL(file);
        // 获取一个路径
        String originName = file.getOriginalFilename();
        // 校验类型
        CheckUtils.checkImage(originName.substring(originName.lastIndexOf(".")));
        String path = MediaUtils.getImageUniquePath(originName);
        CheckUtils.checkNULL(path);
        // 下载文件
        studentInfoService.loadImage(file, path);
        // 返回成功（路径）
//        path = "http://" + redirectDomain + "/" + path;//改为全路径
        return AppResult.success("上传成功", path);
    }

    @ApiOperation(value = "保存草稿", notes = "无data")
    @PostMapping("/save")
    public AppResult saveStudentInfo(HttpServletRequest request,
                                     @ApiParam("微信号") @RequestParam(value = "wxName", required = false) String wxName,
                                     @ApiParam("学号") @RequestParam(value = "studentId", required = false) String studentId,
                                     @ApiParam("姓名") @RequestParam(value = "name", required = false) String name,
                                     @ApiParam("性别") @RequestParam(value = "gender", required = false) Byte gender,
                                     @ApiParam("年级") @RequestParam(value = "grade", required = false) Integer grade,
                                     @ApiParam("专业") @RequestParam(value = "major", required = false) String major,
                                     @ApiParam("班号") @RequestParam(value = "classNumber", required = false) Byte classNumber,
                                     @ApiParam("手机号码") @RequestParam(value = "phone", required = false) String phone,
                                     @ApiParam("备注") @RequestParam(value = "remark", required = false) String remark,
                                     @ApiParam("图片路径") @RequestParam(value = "photo", required = false) String photo,
                                     @ApiParam("加入AchoBeta的理由") @RequestParam(value = "reason", required = false) String reason,
                                     @ApiParam("个人介绍（自我认知）") @RequestParam(value = "introduce", required = false) String introduce,
                                     @ApiParam("个人经历 （项目经历、 职业规划等） ") @RequestParam(value = "experience", required = false) String experience,
                                     @ApiParam("获奖情况") @RequestParam(value = "prize", required = false) String prize) {
        // 判断年级信息是否正确
        if(grade != null && (grade.compareTo(2010) < 0 || grade.compareTo(2030) > 0)) {
            log.warn(ResultCode.FAILED_STUDENT_INFO_GRADE.toString());
            return AppResult.failed(ResultCode.FAILED_STUDENT_INFO_GRADE);
        }
        // 校验性别
        if(gender != null && (gender < 0 || gender > 1)) {
            log.warn(ResultCode.FAILED_STUDENT_INFO_GENDER.toString());
            return AppResult.failed(ResultCode.FAILED_STUDENT_INFO_GENDER);
        }
        // 获取当前登录用户openid
        WxUser wxUser = SessionUtils.getWxUser(request);
        String openid = wxUser.getOpenid();
//        String openid = guy;
        // 获取当前登录用户的简历草稿
        StudentInfo studentInfo = studentInfoService.selectStudentInfoByOpenId(openid, (byte) 0);
        // 校验
        if(studentInfo == null || studentInfo.getDeleteState() == 1) {
            log.warn(ResultCode.FAILED_UNAUTHORIZED.toString());
            return AppResult.failed(ResultCode.FAILED_UNAUTHORIZED);
        }
        // 构造更新对象(允许跟原来一样)
        StudentInfoWithBLOBs updateStudentInfo = new StudentInfoWithBLOBs();
        updateStudentInfo.setId(studentInfo.getId());
        updateStudentInfo.setOpenid(openid);
        updateStudentInfo.setState((byte) 0);
        updateStudentInfo.setWxName(wxName);
        updateStudentInfo.setStudentId(studentId);
        updateStudentInfo.setName(name);
        updateStudentInfo.setGender(gender);
        updateStudentInfo.setGrade(grade);
        updateStudentInfo.setMajor(major);
        updateStudentInfo.setClassNumber(classNumber);
        updateStudentInfo.setPhone(phone);
        updateStudentInfo.setReason(reason);
        updateStudentInfo.setIntroduce(introduce);
        updateStudentInfo.setExperience(experience);
        updateStudentInfo.setPrize(prize);
        updateStudentInfo.setPhoto(photo);
        updateStudentInfo.setRemark(remark);
        updateStudentInfo.setUpdateTime(new Date());
        // 保存草稿
        studentInfoService.saveStudentInfo(updateStudentInfo);
        return AppResult.success();
    }

    @ApiOperation(value = "提交简历/修改已投递的简历", notes = "无data")
    @PostMapping("/submit")
    public AppResult updateStudentInfo(HttpServletRequest request,
                                     @ApiParam("微信号") @RequestParam(value = "wxName", required = false) String wxName,
                                     @ApiParam("学号") @NonNull @RequestParam(value = "studentId") String studentId,
                                     @ApiParam("姓名") @NonNull @RequestParam(value = "name") String name,
                                     @ApiParam("性别") @NonNull @RequestParam(value = "gender") Byte gender,
                                     @ApiParam("年级") @NonNull @RequestParam(value = "grade") Integer grade,
                                     @ApiParam("专业") @NonNull @RequestParam(value = "major") String major,
                                     @ApiParam("班号") @NonNull @RequestParam(value = "classNumber") Byte classNumber,
                                     @ApiParam("手机号码") @NonNull @RequestParam(value = "phone") String phone,
                                     @ApiParam("备注") @RequestParam(value = "remark", required = false) String remark,
                                     @ApiParam("图片路径") @NonNull @RequestParam(value = "photo") String photo,
                                     @ApiParam("加入AchoBeta的理由") @NonNull @RequestParam(value = "reason") String reason,
                                     @ApiParam("个人介绍（自我认知）") @NonNull @RequestParam(value = "introduce") String introduce,
                                     @ApiParam("个人经历 （项目经历、 职业规划等） ") @NonNull @RequestParam(value = "experience") String experience,
                                     @ApiParam("获奖情况") @NonNull @RequestParam(value = "prize") String prize) {
        // 判断年级信息是否正确
        if(grade.compareTo(2010) < 0 || grade.compareTo(2030) > 0) {
            log.warn(ResultCode.FAILED_STUDENT_INFO_GRADE.toString());
            return AppResult.failed(ResultCode.FAILED_STUDENT_INFO_GRADE);
        }
        // 校验性别
        if(gender < 0 || gender > 1) {
            log.warn(ResultCode.FAILED_STUDENT_INFO_GENDER.toString());
            return AppResult.failed(ResultCode.FAILED_STUDENT_INFO_GENDER);
        }
        // 获取当前登录用户openid
        WxUser wxUser = SessionUtils.getWxUser(request);
        String openid = wxUser.getOpenid();
//        String openid = guy;
        // 构造更新对象(允许跟原来一样)
        StudentInfoWithBLOBs updateStudentInfo = new StudentInfoWithBLOBs();
        // 获取当前登录用户的已交简历
        StudentInfo studentInfo = studentInfoService.selectStudentInfoByOpenId(openid, (byte) 1);
        // 校验(避免再次提交)
        if(studentInfo == null || studentInfo.getDeleteState() == 1) {
            updateStudentInfo.setId(null);
        }else {
            updateStudentInfo.setId(studentInfo.getId());
        }
        updateStudentInfo.setOpenid(openid);
        //※※※※※※※  修改为已提交
        updateStudentInfo.setState((byte) 1);
        //※※※※※※※
        updateStudentInfo.setWxName(wxName);
        updateStudentInfo.setStudentId(studentId);
        updateStudentInfo.setName(name);
        updateStudentInfo.setGender(gender);
        updateStudentInfo.setGrade(grade);
        updateStudentInfo.setMajor(major);
        updateStudentInfo.setClassNumber(classNumber);
        updateStudentInfo.setPhone(phone);
        updateStudentInfo.setReason(reason);
        updateStudentInfo.setIntroduce(introduce);
        updateStudentInfo.setExperience(experience);
        updateStudentInfo.setPrize(prize);
        updateStudentInfo.setPhoto(photo);
        updateStudentInfo.setRemark(remark);
        Date date = new Date();
        updateStudentInfo.setUpdateTime(date);
        updateStudentInfo.setCreateTime(date);
        updateStudentInfo.setDeleteState((byte) 0);
        // 提交简历
        studentInfoService.submitStudentInfo(updateStudentInfo);
        // 创建student，manage remark对象，插入t_student，t_manage_remarks表
        return AppResult.success();
    }


    @ApiOperation(value = "获取用户的超详细的信息", notes = "data为用户信息，状态，管理员标记的信息组合")
    @RequestMapping(value = "/detail", method = {RequestMethod.GET, RequestMethod.POST})
    public AppResult<StudentInfoVO> getDetail(HttpServletRequest request,
                                              @NonNull @ApiParam("openid") @RequestParam("openid") String openid) {
        // 获取当前登录的管理员账号
        Manager manager = SessionUtils.getManager(request);
        // 判断是否有权限
        if(!LimitUtils.hasPower(manager, Rule.STUDENT_INFO_DETAIL_RULE)) {
            log.warn(ResultCode.FAILED_MANAGER_NOT_POWERS.toString());
            return AppResult.failed(ResultCode.FAILED_MANAGER_NOT_POWERS);
        }
        // 调用service层
        StudentInfoVO studentInfoVO = studentInfoService.selectDetailStudentInfoByOpenid(openid);
        CheckUtils.checkNULL(studentInfoVO);
        // 返回
        return AppResult.success(studentInfoVO);
    }


    @ApiOperation(value = "管理员修改学生信息", notes = "无data")
    @PostMapping("/modify")
    public AppResult modifyStudentInfo(HttpServletRequest request,
                                       @ApiParam("状态id") @NonNull @RequestParam(value = "stateId") Byte stateId,
                                       @ApiParam("openid") @NonNull @RequestParam(value = "openid") String openid,
                                       @ApiParam("微信号") @RequestParam(value = "wxName", required = false) String wxName,
                                       @ApiParam("学号") @NonNull @RequestParam(value = "studentId") String studentId,
                                       @ApiParam("姓名") @NonNull @RequestParam(value = "name") String name,
                                       @ApiParam("性别") @NonNull @RequestParam(value = "gender") Byte gender,
                                       @ApiParam("年级") @NonNull @RequestParam(value = "grade") Integer grade,
                                       @ApiParam("专业") @NonNull @RequestParam(value = "major") String major,
                                       @ApiParam("班号") @NonNull @RequestParam(value = "classNumber") Byte classNumber,
                                       @ApiParam("手机号码") @NonNull @RequestParam(value = "phone") String phone,
                                       @ApiParam("备注") @RequestParam(value = "remark", required = false) String remark,
                                       @ApiParam("图片路径") @NonNull @RequestParam(value = "photo") String photo,
                                       @ApiParam("加入AchoBeta的理由") @NonNull @RequestParam(value = "reason") String reason,
                                       @ApiParam("个人介绍（自我认知）") @NonNull @RequestParam(value = "introduce") String introduce,
                                       @ApiParam("个人经历 （项目经历、 职业规划等） ") @NonNull @RequestParam(value = "experience") String experience,
                                       @ApiParam("获奖情况") @NonNull @RequestParam(value = "prize") String prize) {
        // 获取当前登录的管理员
        Manager manager = SessionUtils.getManager(request);
        // 判断是否有权限
        if(!LimitUtils.hasPower(manager, Rule.UPDATE_STUDENT_INFO_RULE)) {
            log.warn(ResultCode.FAILED_MANAGER_NOT_POWERS.toString());
            return AppResult.failed(ResultCode.FAILED_MANAGER_NOT_POWERS);
        }
        // 判断年级信息是否正确
        if(grade.compareTo(2010) < 0 || grade.compareTo(2030) > 0) {
            log.warn(ResultCode.FAILED_STUDENT_INFO_GRADE.toString());
            return AppResult.failed(ResultCode.FAILED_STUDENT_INFO_GRADE);
        }
        // 校验性别
        if(gender < 0 || gender > 1) {
            log.warn(ResultCode.FAILED_STUDENT_INFO_GENDER.toString());
            return AppResult.failed(ResultCode.FAILED_STUDENT_INFO_GENDER);
        }
        // 构造更新对象
        StudentInfoWithBLOBs updateStudentInfo = new StudentInfoWithBLOBs();
        // 获取用户的已交简历
        StudentInfo studentInfo = studentInfoService.selectStudentInfoByOpenId(openid, (byte) 1);
        // 校验
        if(studentInfo == null || studentInfo.getDeleteState() == 1) {
            updateStudentInfo.setId(null);
        }else {
            updateStudentInfo.setId(studentInfo.getId());
        }
        updateStudentInfo.setOpenid(openid);
        //※※※※※※※  修改为已提交
        updateStudentInfo.setState((byte) 1);
        //※※※※※※※
        updateStudentInfo.setWxName(wxName);
        updateStudentInfo.setStudentId(studentId);
        updateStudentInfo.setName(name);
        updateStudentInfo.setGender(gender);
        updateStudentInfo.setGrade(grade);
        updateStudentInfo.setMajor(major);
        updateStudentInfo.setClassNumber(classNumber);
        updateStudentInfo.setPhone(phone);
        updateStudentInfo.setReason(reason);
        updateStudentInfo.setIntroduce(introduce);
        updateStudentInfo.setExperience(experience);
        updateStudentInfo.setPrize(prize);
        updateStudentInfo.setPhoto(photo);
        updateStudentInfo.setRemark(remark);
        Date date = new Date();
        updateStudentInfo.setUpdateTime(date);
        updateStudentInfo.setCreateTime(date);
        updateStudentInfo.setDeleteState((byte) 0);
        // 调用service层修改
        studentInfoService.updateInfo(updateStudentInfo, stateId);
        // 成功
        return AppResult.success();
    }

}
